package com.tianyang.yukuaifuzs.jump.oss;

import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.tianyang.yukuaifuzs.base.YkfApplication;
import com.tianyang.yukuaifuzs.common.interfaces.IUploadFileCallback;
import com.tianyang.yukuaifuzs.utils.DateUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * Description：oss上传工具类
 * Created by xyj on 2024/3/15
 */
public class AliyunOSSUtils {

    private static AliyunOSSUtils mOSSUtils;
    private UploadListener listener;
    private static OSS oss;

    /**
     * 单一实例
     */
    public static AliyunOSSUtils getInstance() {

        if (mOSSUtils == null) {
            synchronized (AliyunOSSUtils.class) {
                if (mOSSUtils == null) {
                    mOSSUtils = new AliyunOSSUtils();
                }

            }
        }
        return mOSSUtils;
    }

    public AliyunOSSUtils() {
        // 配置类如果不设置，会有默认配置。
        OSSPlainTextAKSKCredentialProvider provider = new OSSPlainTextAKSKCredentialProvider(MyOSSConfig.OSS_ACCESS_KEY_ID, MyOSSConfig.OSS_ACCESS_KEY_SECRET);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒。
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒。
        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个。
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次。
        oss = new OSSClient(YkfApplication.getInstance(), MyOSSConfig.OSS_EXTERNAL_ENDPOINT, provider, conf);
    }

    public String getFileName(String photoType, String userId) {
        //ykf + android +  userId + YYYYMMddHHmmss + 四位随机数.png
        String checkValue = ((int) (Math.random() * 9000) + 1000) + "";
//        return  "ykfandroid" + userId + DateUtils.getCurrentTime("YYYYMMddHHmmss") + checkValue + ".png";
        return  photoType + "_ykfandroid" + userId + DateUtils.getCurrentTime("YYYYMMddHHmmss") + checkValue + ".png";
    }

    /**
     * 上传单个文件
     *
     * @param name
     * @param localPath
     */
    public String uploadFile(String name, String localPath, IUploadFileCallback callback) {
        // 构造上传请求。
        PutObjectRequest put = new PutObjectRequest(MyOSSConfig.BUCKET_NAME, MyOSSConfig.PREFIX+ name, localPath);
        // 异步上传时可以设置进度回调。
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("AliyunOSS", "PutObject="+ "currentSize: " + currentSize + " totalSize: " + totalSize);
                if (callback != null)
                    callback.callback(currentSize, totalSize);
            }
        });
        try {
            // 开始同步上传
            PutObjectResult result = oss.putObject(put);
            Log.d("AliyunOSS", "upload: result=" + result);
            // 得到一个外网可访问的地址
            String url = oss.presignPublicObjectURL(MyOSSConfig.BUCKET_NAME, MyOSSConfig.PREFIX+ name);
//            if (listener != null)
//                listener.onUpLoadComplete(url);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //上传多个文件
    public void upLoadMultipleFile(String name, String path) {
        // 构造上传请求。
        PutObjectRequest put = new PutObjectRequest(MyOSSConfig.BUCKET_NAME, name, path);

        // 异步上传时可以设置进度回调。
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("AliyunOSS", "PutObject=currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("AliyunOSS", "PutObject:UploadSuccess");
                Log.d("AliyunOSS", "ETag："+result.getETag());
                Log.d("AliyunOSS", "RequestId："+ result.getRequestId());
                String url = oss.presignPublicObjectURL(MyOSSConfig.BUCKET_NAME, name);

                Log.e("AliyunOSS", "图片地址--------------"+ url + "-----------------");
                if (listener != null)
                    listener.onUpLoadComplete(url);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等。
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常。
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        // task.cancel(); // 可以取消任务。
        // task.waitUntilFinished(); // 等待上传完成。
    }

    public void setUpLoadListener(UploadListener listener) {
        this.listener = listener;
    }

    /**
     * 下载文件
     *
     * @param name
     */
    public void downLoadFile(String name) {
        // 构造下载文件请求。
        GetObjectRequest get = new GetObjectRequest(MyOSSConfig.BUCKET_NAME, name);
        OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                // 请求成功。
                Log.d("asyncGetObject", "DownloadSuccess");
                Log.d("Content-Length", "" + result.getContentLength());

                InputStream inputStream = result.getObjectContent();
                byte[] buffer = new byte[2048];
                int len;

                try {
                    while ((len = inputStream.read(buffer)) != -1) {
                        // 您可以在此处编写代码来处理下载的数据。

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            // GetObject请求成功，将返回GetObjectResult，其持有一个输入流的实例。返回的输入流，请自行处理。
            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等。
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常。
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        // task.cancel(); // 可以取消任务。
        // task.waitUntilFinished(); // 等待任务完成。
    }

    public interface UploadListener {
        void onUpLoadComplete(String url);
    }
}
